import axios from "axios";
import { ElMessage } from "element-plus";
import "element-plus/theme-chalk/el-message.css";
import { useUserStore } from "@/stores/user.js"
import router from "@/router";

const httpInstance = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 30000
})
httpInstance.interceptors.request.use(config => {
  // 1. 从pinia获取token数据
  const userStore = useUserStore()
  // 2. 按照后端的要求拼接token数据
  const token = userStore.userInfo.token
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, e => Promise.reject(e))

httpInstance.interceptors.response.use( 
  (res) => res.data,
  (e) => {
    // 这里通过拦截器的方式，来发送提示信息，
    // 这个response是拦截到响应码不是200了就会执行这个
    const userStore = useUserStore()
    if(e.message){
      ElMessage.error(e.message)
    }else{
      if(e.response?.data?.message){
        ElMessage({
          type: "warning",
          message: e.response.data.message
        });
      }
    }
    //当返回错误码是401时 代表token过期 此时清除用户登录信息 并跳转到登录页面重新登录 
    if (e.response?.status === 401) {
      userStore.clearUserInfo
      router.push('/login')
    }
    return Promise.reject(e);
  }
);
export default httpInstance